# coding: utf-8
__author__ = 'pyTomato'

import json
import time
from django.http.response import HttpResponse, HttpResponseBadRequest
from analysis.utils import exceptions


@exceptions.catch_exception
def wifi_sense(request):
    req = json.loads(request.body.decode())
    flag = req["flag"]
    if flag == "request_server":
        gw_id = req["apMac"]
        requestId = req["requestId"]

        reply = {
            "flag": flag,
            "apMac": gw_id,
            "requestId": requestId,
            "server_time": str(round(time.time())),
            "report_interval": "300"
        }

        #print(reply)

        return HttpResponse(json.dumps(reply))
    elif flag == "report_rssi":
        onlineNum = req["onlineNum"]
        gw_id = req["apMac"]
        print(req)
        my = My()

        sql = 'INSERT INTO app_wifiprobe (gw_id, online, create_time, modified_time) VALUES ("{0}", "{1}", UTC_TIMESTAMP(), UTC_TIMESTAMP())'.format(gw_id, onlineNum)
        my.execute(sql)
        wifi_probe_id = my.insert_id()

        rssi_info = req["rssiinfo"]
        print(rssi_info)

        for rec in rssi_info:
            rec = rec.split('|')
            mac = rec[0]
            rssi_max = rec[1]
            rssi_max_timestamp = rec[2]
            rssi_min = rec[3]
            rssi_min_timestamp = rec[4]
            sql = 'INSERT INTO app_wifidevice (mac, rssi_max, rssi_max_timestamp, rssi_min, rssi_min_timestamp, create_time, modified_time, wifi_probe_id) VALUES ' \
                  '("{0}", "{1}", "{2}", "{3}", "{4}", UTC_TIMESTAMP(), UTC_TIMESTAMP(), "{5}")'.format(mac, rssi_max, rssi_max_timestamp, rssi_min, rssi_min_timestamp, wifi_probe_id)
            my.execute(sql)
        my.commit()
        my.close()
        return HttpResponse("OK")
    else:
        return HttpResponseBadRequest
